<div class="layui-row">
  <div class="layui-col-lg3">
    <div class="layui-btn-group" id="device_handle_permi">
      <button class="layui-btn data_handle_btn">添加</button>
      <button class="layui-btn device_deliver">转移</button>
      <button type="button" class="layui-btn" id="file_input_btn"><i class="layui-icon"></i>文件导入</button>
    </div>
  </div>
  <div class="layui-col-lg3">
    <form class="layui-form layui-form-pane" action="">
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <input type="text" l name="search_key"  placeholder="设备ID/名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <a class="layui-btn" lay-submit="" lay-filter="data-search-btn">搜索</a>
            </div>
        </div>
    </form>
  </div>
</div>

<table class="layui-table" id="base_info_manage_table" lay-filter="base_info_manage_table"></table>
<script type="text/html" id="table_info_handle_bar">
    <a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs layui-btn-danger data-count-edit" lay-event="del">删除</a>
    <!-- <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">启/停</a> -->
</script>

<script type="text/html" id="table_header">
  <p>人员管理表</p>
</script>

<!-- 添加数据表单开始 -->
<form  class="layui-form layui-form-pane " action="" id="handle_data_form" lay-filter="handle_data_form" style="padding: 10px;display: none;">
  <div class="lauyi-row">
    <div class="layui-col-lg6">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">姓名</label>
          <div class="layui-input-block">
            <input type="text" name="name" lay-verify="required" lay-reqtext="必填项!" placeholder="保存后，禁止重复/更改" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>

       <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">电话</label>
          <div class="layui-input-block">
            <input type="text" lay-verify="phone" name="phone" placeholder="必须项" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">性别</label>
          <div class="layui-input-block">
            <input type="radio" name="sex" value="男" title="男" checked="">
            <input type="radio" name="sex" value="女" title="女">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">年龄</label>
          <div class="layui-input-block">
            <input type="text" name="person_age" placeholder="年龄" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">部门</label>
          <div class="layui-input-block">
            <input type="text" name="department"  autocomplete="off" placeholder="所在部门" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">角色</label>
          <div class="layui-input-block">
            <input type="text" name="character"  autocomplete="off" placeholder="职位等" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item" >
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green" >使用设备ID</label>
          <div class="layui-input-block" >
            <input id="bind_device" name="device_id" type="text" list="bind_device_list"  name="tml_serch"  placeholder="选择设备" autocomplete="off" class="layui-input">
              <datalist id="bind_device_list"></datalist>
          </div>
        </div>
      </div>

     
    </div>

    <div class="layui-col-lg6">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">照片</label>
          <div class="layui-input-block">
            <!-- <input type="text" name="picture" style="display: none;"> -->
            <img type="text" src="" style="width:180px;height:180px" id="picture">
          </div>
        </div>
      </div>

       <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">人员编号</label>
          <div class="layui-input-block">
            <input type="text" name="person_id"  placeholder="自定义编号" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>


      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">备注</label>
          <div class="layui-input-block">
            <input type="text" name="remark" placeholder="备注信息" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>
    </div>
  </div>

  <button class="layui-btn layui-btn-fluid" id="add_submit_btn" lay-submit lay-filter="add_submit" >提交</button>

</form>

<!-- 添加数据表单结束 -->

<!-- 修改数据表单开始 -->
<form  class="layui-form layui-form-pane " action="" id="edit_data_form" lay-filter="edit_data_form" style="padding: 10px;display: none;">
  <div class="lauyi-row">
    <div class="layui-col-lg6">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">姓名</label>
          <div class="layui-input-block">
            <input readonly="readonly" id="person_name" type="text" name="name" lay-verify="required" lay-reqtext="必填项!" placeholder="必填" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">电话</label>
          <div class="layui-input-block">
            <input type="text" lay-verify="phone" name="phone" placeholder="电话" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">性别</label>
          <div class="layui-input-block">
            <input type="radio" name="sex" value="男" title="男" checked="">
            <input type="radio" name="sex" value="女" title="女">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">年龄</label>
          <div class="layui-input-block">
            <input type="text" name="person_age" placeholder="年龄" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">部门</label>
          <div class="layui-input-block">
            <input type="text" name="department"  autocomplete="off" placeholder="所在部门" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">角色</label>
          <div class="layui-input-block">
            <input type="text" name="character"  autocomplete="off" placeholder="职位等" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item" >
        <div class="layui-inline" id="person_bind_dev">
          <label class="layui-form-label layui-bg-green" >使用设备ID</label>
          <div class="layui-input-inline" >
            <input id="change_device" name="device_id" type="text" list="change_device_list"  name="tml_serch"  placeholder="选择设备" autocomplete="off" class="layui-input">
              <datalist id="change_device_list"></datalist>
          </div>
          <div class="layui-form-mid layui-word-aux">—</div>
          <a class="layui-btn" onclick="dismiss_dev($('#change_device').val(),$('#person_name').val())">解绑</a>
        </div>
      </div>

    </div>
    <div class="layui-col-lg6">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">照片</label>
          <div class="layui-input-block">
            <input type="text" name="picture" style="display: none;" value="0">
            <img type="text" src="" style="width:180px;height:180px" id="edit_picture">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">人员编号</label>
          <div class="layui-input-block">
            <input type="text" name="person_id"  placeholder="自定义编号" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label layui-bg-green">备注</label>
          <div class="layui-input-block">
            <input type="text" name="remark" placeholder="备注信息" autocomplete="off" class="layui-input">
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <button class="layui-btn layui-btn-fluid" id="edit_submit_btn" lay-submit lay-filter="edit_submit" >提交</button>
</form>

<!-- 修改数据表单结束 -->

<!-- 设备转移表单 开始-->
<div class="layui-container" id="device_deliver_div" style="display: none;padding: 20px">
    <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green" style="text-align: center;">转移到</label>
      <div class="layui-input-block">
       <input type="text" list="deliver_target" name="" class="layui-input" id="dev_to_user">
        <datalist id="deliver_target">
        </datalist>
      </div>
    </div>
  </div>
  <table id="user_tree"  class="layui-table"></table>
</div>
<!-- 设备转移表单 结束-->

<!-- 设备导入处理开始 -->
<div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">id</label>
      <div class="layui-input-block">
        <input type="text" name="device_input"  autocomplete="off" class="layui-input" id="device_input">
      </div>
    </div>
</div>
<!-- 设备导入处理结束 -->

<!-- 引入把上传的表格转变为json的插件 -->
<script src="/static/js/xlsx.js"></script>
<!-- js代码开始 -->

<script type="text/javascript">
if(user_permi==='普通用户'){
  $('#device_handle_permi').hide()
}
var ajax_url='person_manage'
// 设备数据表格渲染函数
var table_show=function(table_data){
  table.render({
    elem: '#base_info_manage_table',
    toolbar:'#table_header',
    data: table_data,
    id:'base_info_manage_table',
    cols: [[
        {type: "checkbox", fixed: "left"},
        // {field: 'id', title: 'ID',width:20,sort:true},
        {field: 'name', title: '名字',sort:true},
        {field: 'phone', title: '电话',sort:true,templet:function(row){

          var person_detail=eval('('+row.detail+')')
          // console.log(person_detail)
          return person_detail.phone
        }},
        {field: 'sex', title: '性别',sort:true,templet:function(row){

          var person_detail=eval('('+row.detail+')')
          // console.log(person_detail)
          return person_detail.sex
        }},
        {field: 'person_age', title: '年龄',sort:true,templet:function(row){

          var person_detail=eval('('+row.detail+')')
          // console.log(person_detail)
          return person_detail.person_age
        }},
        {field: 'department', title: '部门',sort:true,templet:function(row){
          var person_detail=eval('('+row.detail+')')
          return person_detail.department
        }},
        {field: 'character', title: '角色',sort:true,templet:function(row){
          var person_detail=eval('('+row.detail+')')
          return person_detail.character
        }},
        {field: 'person_id', title: '人员编号',templet:function(row){
          var person_detail=eval('('+row.detail+')')
          return person_detail.person_id
        }},
        {field: 'device_id', title: '使用设备ID',sort:true},
        {field: 'person_detail', title: '照片',sort:true,templet:function(row){
          var detail=eval('('+row.detail+')')
          if(detail.picture=='0' | detail.picture==null){
            return ''
          }
          var picture='/static/data_from_web/picture/person/'+detail.picture
          var detail_show='<img src="'+picture+'" style="width:150px">'
          return detail_show
        }},
        {field: 'owner', title: '用户',sort:true},
        {field: 'remark', title: '备注'},
        {field: 'date_added', title: '添加时间',sort:true},
        {title: '操作', minWidth: 110, templet: '#table_info_handle_bar', fixed: "right", align: "center"}
    ]],
    limits: [10, 15, 20, 25, 50, 100],
    limit: 10,
    page: true
  });
}

// 首次用户数据加载
var person_data;
var dev_data;
var hadle_get_func=function(data){
  console.log(data)
  person_data=data.person_data
  dev_data=data.dev_data
  table_show(person_data)
}
// 首次用户数据加载,index页面加载设备和型号信息
get_info_ajax(ajax_url,'get_init_data',hadle_get_func)

// 监听添加操作
$(".data_handle_btn").on("click", function () {
    document.getElementById("handle_data_form").reset();
    form.render();
    // 人员图片上传功能
    img_upload_func('picture')
    fill_option(dev_data,'bind_device_list','device_id')
    layer.open({
        type: 1
        ,title:'新增人员信息'
        ,area:['920px','550px']
        ,offset:'60px'  
        ,id: 'add_data' //防止重复弹出
        ,content:$('#handle_data_form')
        ,shade: 0 //不显示遮罩
      });
});

// 监听添加操作,并提交
form.on('submit(add_submit)',function(obj){
  var base_info=package_data(obj.field)
  console.log(base_info)
  post_info_ajax(base_info,ajax_url,'add',table_show)
  return false
})


// 监听操作按钮，编辑/启停
table.on('tool(base_info_manage_table)', function (obj) {
  // 渲染图片框，点击可以选择图片
  $('#edit_picture').attr('src','')
  img_upload_func('edit_picture')
  var result = obj.data;
  if(obj.event=='edit'){
    var detail=eval('('+result.detail+')')
    result = $.extend(result,detail)
    var picture_path=detail['picture']
    if(picture_path!=='0'){
      $('#edit_picture').attr('src','/static/data_from_web/picture/person/'+detail['picture'])
    }

    if(result.device_id!=='' && result.device_id!=='0'){
      $('#change_device').attr('readonly','readonly')
    }else{
      fill_option(dev_data,'change_device_list','device_id')
    }
    result['picture']=picture_path
    document.getElementById("edit_data_form").reset();
    form.val('edit_data_form',result)

    layer.open({
      type: 1
      ,area:['920px','550px']
      ,offset:'60px'  //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
      ,id: 'edit_data' //防止重复弹出
      ,content:$('#edit_data_form')
      ,shade: 0 //不显示遮罩
    });
  }else if(obj.event=='del'){
    layer.confirm("确定删除人员："+result.name+"？",
              {btn: ['是', '否']}, 
              function (index) {
                post_info_ajax(result,ajax_url,'del',table_show)
              }
              ,function(){
                console.log('no')
                layer.closeAll()
              });
  }
});


// 监听修改操作,并提交
form.on('submit(edit_submit)',function(obj){
  // console.log(obj.field)
  var base_info=package_data(obj.field)
  // console.log(base_info)
  post_info_ajax(base_info,ajax_url,'edit',table_show)
  return false
})

// 解除绑定设备
var dismiss_dev=function(device_id,user_name){
  $('#change_device').removeAttr('readonly')
  $('#change_device').val('')
  fill_option(dev_data,'change_device_list','device_id')
}

//封装数据
var package_data=function(result,handle_kind='add'){
  var base_data={}
  base_data['name']=result['name']
  base_data['device_id']=result['device_id']
  base_data['remark']=result['remark']
  var person_detail={}
  if(result.picture==null){
    if (result['file']==""){
      console.log('no_picture')
      person_detail['picture']='0'
    }else{
      person_detail['picture']=$('#picture')[0].src
    }
  }else{
    if (result['file']==""){
      console.log('no_new_picture')
      person_detail['picture']=result.picture
    }else{
      person_detail['picture']=$('#edit_picture')[0].src
    }
  }
  person_detail['sex']=result['sex']
  person_detail['phone']=result['phone']
  person_detail['person_age']=result['person_age']
  person_detail['department']=result['department']
  person_detail['character']=result['character']
  person_detail['person_id']=result['person_id']
  base_data['detail']=person_detail
  return base_data
}

// 获取设备数据表格选中的数据，弹出用户结构弹窗，选择转移的目标用户，提交后台处理
$('.device_deliver').click(function(){
  var data_check=table.checkStatus('base_info_manage_table').data
  if(data_check.length===0){
    layer.msg('请选择需要转移的设备')
    return false
  }
  // 渲染用户树形结构
  tree.render({
    elem: '#user_tree'
    ,data: user_tree
    ,showCheckbox: false  //是否显示复选框
    ,id: 'id'
    ,onlyIconControl:true
    ,isJump: false //是否允许点击节点时弹出新窗口跳转
    ,text: {
            defaultNodeName: '未命名' //节点默认名称
            ,none: '无数据' //数据为空时的提示文本
          }   
    ,click: function(obj){
      var data = obj.data;  //获取当前点击的节点数据

      // console.log(data)
      if(data['name']=='all'){
        layer.msg('该选择无效！')
        return false
      }
      $('#dev_to_user').val(data['name'])
    }

  });
  // 加载所有下级用户名称
  for(var i=0;i<user_data.length;i++){
    var user_name_option='<option>'+user_data[i]['visible_name']+'</option>'
    $('#deliver_target').append(user_name_option)
  }
// 弹窗，展示用户树形结构，选择用户，提交后台
  layer.open({
        type: 1
        ,title:'设备转移'
        ,area:['400px','500px']
        ,offset:'60px'  
        ,id: 'device_deliver' //防止重复弹出
        ,content:$('#device_deliver_div')
        ,btn: ['提交','关闭']
        ,shade: 0 //不显示遮罩
        ,btn1: function(){
            var result={};
            var target_user=$('#dev_to_user').val()
            var dev_to_user=[]
            for(var i=0;i<data_check.length;i++){
              dev_to_user.push(data_check[i]['name'])
            }
            result['name']=dev_to_user
            result['target_user']=target_user
            layer.confirm('被转移人员数据，设备绑定关系清空，确定转移到'+target_user+'?', function (index) {
              post_info_ajax(result,ajax_url,'change_owner',table_show)
            })
        }
        ,btn2: function(){
          layer.closeAll();
        }
      });

})

// 监听 导入文件 按钮，做展示和修改操作处理
$('#file_input_btn').click(function(){
  var input = document.createElement('input');
  input.type = 'file';

  input.addEventListener('change', function() {
    var file = this.files[0];
    var reader = new FileReader();

    reader.onload = function (e) {
      var data = e.currentTarget.result;
      var wb = XLSX.read(data,{type:'binary'})
      var j_data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
      console.log(j_data)
      if(j_data[0]['__EMPTY']!=null){
        layer.msg('表格出错')
        return false
      }

      var batch_add_data=[];
      for(var i=0;i<j_data.length;i++){
         if(j_data[i]['name']!==0 && j_data[i]['name']!=='0'  && j_data[i]['name']!=='' && j_data[i]['name']!=null){
          batch_add_data.push(j_data[i])
         }  
      }

      layer.confirm('确定导入'+batch_add_data.length.toString()+'条人员信息', function (index) {
        // console.log(batch_add_data)
        base_info_ajax(batch_add_data,ajax_url,'add_from_file')

      })

    }
    reader.readAsBinaryString(file)
  })

    input.click();
})


// 监听设备搜索操作
form.on('submit(data-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(person_data,search_key,'name','device_id')
    // 表格重载
    table_show(search_result)
  }else{
    table_show(person_data)
  }
  return false;
});


</script>